<?php include_once( "_db.php" ); //Database ?>
<?php include_once( "funcdef.php" ); //Functions Definition ?>
<?php include_once( "header.php" ); //Header ?>
<?php include_once( "footer.php" ); //Footer ?>
<?php
//include page header
header_template("Postage", $_SERVER['PHP_SELF'], "icon-th-large");

//db OBJECT invoked!
$db = new DATABASE();
?>
      <div class="row">
        <div class="span6">
<?php
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
  //Submit button for Create
  $button_submit_name  = "create-postage";
  $button_submit_value = "Create";
  //Hidden postage id
  $hidden_postage_id = "";
  //Postage for Create
  $resPostg = array();
  if (isset($_GET["action"]) && isset($_GET["postg_id"])) {
    if ($_GET["action"] == "edit") {
      //Postage for Edit
      //construct SELECT query
      $conds = array();
      $conds[] = array(0); //$param_col;
      $conds[] = array(0); //$param_op;
      $conds[] = array($_GET["postg_id"]); //$param_key;
      $query = $db->db_select("postage", NULL, $conds);
      //execute SELECT query
      $result = $db->database->query($query);
      //result SELECT query
      $resPostg = $result->fetchAll(SQLITE_ASSOC);
      //Submit button for Edit
      $button_submit_name  = "edit-postage";
      $button_submit_value = "Edit";
      //Hidden postage id
      $hidden_postage_id = "<input type='hidden' name='postage_id' value='".$resPostg[0]['postage_id']."' />";
    }
  }
//Postage Form
?>
          <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" enctype="application/x-www-form-urlencoded" class="form-horizontal">
            <?php echo $hidden_postage_id."\n"; ?>
            <fieldset>
              <div class="control-group">
                <label class="control-label" for="postage_country_name">Postage Country</label>
                <div class="controls">
                  <input type="text" class="input-xlarge" id="postage_country_name" name="postage_country_name" value="<?php echo $resPostg[0]['postage_country_name']; ?>">
                </div>
              </div>
              <div class="control-group">
                <label class="control-label" for="postage_country_price">Postage Country Price</label>
                <div class="controls">
                  <div class="input-prepend">
                  <span class="add-on">MYR</span><input type="text" class="input-mini" id="postage_country_price" name="postage_country_price" value="<?php echo $resPostg[0]['postage_country_price']; ?>">
                  </div>
                </div>
              </div>
              <div class="control-group">
                <label class="control-label" for="postage_country_code">Postage Country Code</label>
                <div class="controls">
                  <input type="text" class="input-mini" id="postage_country_code" name="postage_country_code" value="<?php echo $resPostg[0]['postage_country_code']; ?>">
                  <span class="help-inline">Two-letter <abbr title="ISO-3166">country code</abbr> <a class="label label-default" href="http://www.iso.org/iso/country_codes.htm">ext link</a></span>
                </div>
              </div>
              <div class="form-actions">
                <input type="submit" name="<?php echo $button_submit_name; ?>" value="<?php echo $button_submit_value; ?>" class="btn btn-info" />
              </div>
            </fieldset>
          </form>
<?php
} elseif ($_SERVER['REQUEST_METHOD'] == 'POST') {
  //Create Postage
  if ($_POST['create-postage'] == "Create") {
    //Form field check NG
    if ($_POST["postage_country_name"] == "") {
      printAlert("error", "Oh snap!", "Postage Country field is empty.", $_SERVER['PHP_SELF']);
    } elseif ($_POST["postage_country_price"] == "") {
      printAlert("error", "Oh snap!", "Postage Country Price field is empty.", $_SERVER['PHP_SELF']);
    } elseif (!is_numeric($_POST["postage_country_price"])) {
      printAlert("error", "Oh snap!", "Postage Country Price is not numeric.", $_SERVER['PHP_SELF']);
    } elseif ($_POST["postage_country_code"] == "") {
      printAlert("error", "Oh snap!", "Postage Country Code field is empty.", $_SERVER['PHP_SELF']);
    } else {//Form field check OK
      //construct INSERT query
      $params = array();
      $params[] = array(1, 2, 3); //$param_col;
      $params[] = array($_POST["postage_country_name"], $_POST["postage_country_code"], $_POST["postage_country_price"]); //$param_key;
      $query = $db->db_insert("postage", $params);
      //execute INSERT query
      $result = $db->database->query($query);
      //Add postage NG
      if ($result == FALSE) {
        printAlert("error", "Oh snap!", "Cannot create Postage '".$_POST["postage_country_name"]."'.", $_SERVER['PHP_SELF']);
      } else {//Add postage OK
        //INSERT SUCCEED!!!
        printAlert("success", "Well done!", "Postage '".$_POST["postage_country_name"]."' successfully created.", $_SERVER['PHP_SELF']);
      }
    }
  }
  //Edit Postage
  if ($_POST['edit-postage'] == "Edit") {
    //Form field check NG
    if ($_POST["postage_country_name"] == "") {
      printAlert("error", "Oh snap!", "Postage Country field is empty.", $_SERVER['PHP_SELF']);
    } elseif ($_POST["postage_country_price"] == "") {
      printAlert("error", "Oh snap!", "Postage Country Price field is empty.", $_SERVER['PHP_SELF']);
    } elseif (!is_numeric($_POST["postage_country_price"])) {
      printAlert("error", "Oh snap!", "Postage Country Price is not numeric.", $_SERVER['PHP_SELF']);
    } elseif ($_POST["postage_country_code"] == "") {
      printAlert("error", "Oh snap!", "Postage Country Code field is empty.", $_SERVER['PHP_SELF']);
    } else {//Form field check OK
      //construct UPDATE query
      $params = array();
      $params[] = array(1, 2, 3); //$param_col;
      $params[] = array($_POST["postage_country_name"], $_POST["postage_country_code"], $_POST["postage_country_price"]); //$param_key;
      $conds = array();
      $conds[] = array(0); //$param_col;
      $conds[] = array(0); //$param_op;
      $conds[] = array($_POST["postage_id"]); //$param_key;
      $query = $db->db_update("postage", $params, $conds);
      //execute UPDATE query
      $result = $db->database->query($query);
      //Edit postage NG
      if ($result == FALSE) {
        printAlert("error", "Oh snap!", "Cannot edit Postage '".$_POST["postage_country_name"]."'.", $_SERVER['PHP_SELF']);
      } else {//Edit postage OK
        //UPDATE SUCCEED!!!
        printAlert("success", "Well done!", "Postage '".$_POST["postage_country_name"]."' successfully edited.", $_SERVER['PHP_SELF']);
      }
    }
  }
} else {
  $error_msg = "This script only works with GET and POST requests.";
  printAlert("error", "Oh snap!", $error_msg, $_SERVER['PHP_SELF']);
}

//Delete Postage
if (isset($_GET["action"]) && isset($_GET["postg_id"])) {
  if ($_GET["action"] == "delete") {
    //CHECK FOR bill2postage
    $conds = array();
    $conds[] = array(0); //$param_col;
    $conds[] = array(0); //$param_op;
    $conds[] = array($_GET["postg_id"]); //$param_key;
    $query = $db->db_select("postage", NULL, $conds);
    //execute SELECT query
    $result = $db->database->query($query);
    //result SELECT query
    $resPostg = $result->fetchAll(SQLITE_ASSOC);
    //construct DELETE query
    $query = $db->db_delete("postage", $conds);
    //execute DELETE query
    $result = $db->database->query($query);
    //delete postage NG
    if ($result == FALSE) {
      printAlert("error", "Oh snap!", "Cannot delete ".$resPostg[0]['postage_country_name'], $_SERVER['PHP_SELF']);
    } else {//delete postage OK
      //DELETE SUCCEED!!!
      printAlert("success", "Well done!", $resPostg[0]['postage_country_name']." successfully deleted", $_SERVER['PHP_SELF']);

      //construct DELETE params
      //$conds = array();
      //$conds[] = array(2); //$param_col;
      //$conds[] = array(0); //$param_op;
      //$conds[] = array($_GET["postg_id"]); //$param_key;

      //construct DELETE query
      //$query = $db->db_delete("bill2postage", $conds);
      //execute DELETE query
      //$result = $db->database->query($query);
      /*
      if ($result == FALSE) {
        printAlert("error", "Oh snap!", "Cannot delete ".$resPostg[0]['postage_country_name'], $_SERVER['PHP_SELF']);
      } else {//delete postage OK
        //DELETE SUCCEED!!!
        printAlert("success", "Well done!", $resPostg[0]['postage_country_name']." successfully deleted", $_SERVER['PHP_SELF']);
      }
      */
    }
  }
}

//Pagination
//set number of postg / page
$postgPerPage = 6;
//initialize current page
$curPage = 0;
//set first page
$firstPage = 1;
//initialize last page
$query = "SELECT Count(*) FROM postage";
$rowCount = $db->database->query($query);
$rowCount = $rowCount->fetchAll(SQLITE_NUM);
$rowCount = intval($rowCount[0][0]);
$remainder = intval($rowCount % $postgPerPage);
$lastPage = intval($rowCount / $postgPerPage);
//set current page
if ((isset($_GET["page"])) && (is_numeric($_GET["page"]))) {
  $curPage = intval($_GET["page"]);
} else {
  $curPage = $firstPage;
}
//set last page
if ($remainder > 0) {
  $lastPage++;
}
if ($lastPage > 1) { //pagination start
?>
          <ul class="pager">
<?php
  if ($curPage != $firstPage) {
    $pager_prev_state = " active";
    $pager_prev_href  = " href=\"".$_SERVER['PHP_SELF']."?page=".($curPage-1)."\"";
  } else {
    $pager_prev_state = " disabled";
    $pager_prev_href  = "";
  }

  if ($curPage != $lastPage) {
    $pager_next_state = " active";
    $pager_next_href  = " href=\"".$_SERVER['PHP_SELF']."?page=".($curPage+1)."\"";
  } else {
    $pager_next_state = " disabled";
    $pager_next_href  = "";
  }
?>
            <li class="previous <?php echo $pager_prev_state; ?>">
              <a<?php echo $pager_prev_href; ?>>&larr; Prev</a>
            </li>
            <li class="next <?php echo $pager_next_state; ?>">
              <a<?php echo $pager_next_href; ?>>Next &rarr;</a>
            </li>
          </ul>
          <center>
            <p><span class="label label-info">Page <?php echo $curPage; ?>/<?php echo $lastPage; ?></span></p>
          </center>
<?php } //pagination end ?>
          <table class="table table-condensed table-striped">
            <thead>
              <tr>
                <th>Postage Country</th>
                <th>Postage Country Price</th>
                <th>Postage Country Code</th>
                <th>&nbsp;</th>
              </tr>
            </thead>
            <tbody>
<?php
//construct SELECT query
$query = $db->db_select("postage", NULL, NULL);
//execute SELECT query
$result = $db->database->query($query." ORDER BY postage_id DESC LIMIT ".(($curPage-1)*$postgPerPage).", ".$postgPerPage);
/*$result = $db->database->query($query." ORDER BY postage_id DESC");*/
//result SELECT query
$postages = $result->fetchAll(SQLITE_ASSOC);
//List postage(s)
//Postage(s) existence OK
if (!empty($postages)) {
  //loop trough all postage(s)
  foreach ($postages as $postg) {
    $postage_edit_href = $_SERVER['PHP_SELF']."?action=edit&postg_id=".$postg['postage_id'];
    $postage_delete_href = $_SERVER['PHP_SELF']."?action=delete&postg_id=".$postg['postage_id'];
?>
              <tr>
                <td><?php echo $postg['postage_country_name']; ?></td>
                <td><?php echo $postg['postage_country_price']; ?></td>
                <td><?php echo $postg['postage_country_code']; ?></td>
                <td>
                  <a class="btn btn-success btn-mini" href="<?php echo $postage_edit_href; ?>">Edit</a>
                  <a class="btn btn-danger btn-mini" href="<?php echo $postage_delete_href; ?>">Delete</a>
                </td>
              </tr>
<?php
  }
}
?>
            </tbody>
          </table>
        </div>
      </div>
<?php
//include page footer
footer_template();
?>
